

#import "ImageLoader.h"
#import "RoundedRectImageCreater.h"

@implementation ImageLoader

- (id)init
{
	self = [super init];
	if(self)
	{
		_cache = [[NSMutableDictionary alloc] initWithCapacity:20];
		_activeDownloads = [[NSMutableDictionary alloc] initWithCapacity:20];
	}
	
	return self;
}


+ (ImageLoader*)sharedLoader
{
	static ImageLoader *loader;
	if(!loader)
		loader = [[ImageLoader alloc] init];
	
	return loader;
}

- (UIImage*)imageWithURL:(NSString*)url
{
	UIImage *image = [_cache objectForKey:url];
	if(image) return image;
	
	NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
	if(!imageData) return nil;
	
	image = [UIImage imageWithData:imageData];
	if(image)
		[_cache setObject:image forKey:url];
	
	return image;
}

- (void)setImageWithURL:(NSString*)url toView:(UIImageView*)imageView
{
	UIImage *image = [_cache objectForKey:url];
	if(image)
	{
		imageView.image = image;
		return;
	}
	
	NSMutableArray *pendingViews = [_activeDownloads objectForKey:url];
	if(pendingViews)
	{
		[pendingViews addObject:imageView];
	}
	else
	{
//		ImageDownloader *downloader = [[ImageDownloader alloc] init];
		ImageDownloaderASI *downloader = [[ImageDownloaderASI alloc] init];
		[downloader getImageFromURL:url delegate:self];
		[downloader release];
		pendingViews = [NSMutableArray arrayWithObject:imageView];
		[_activeDownloads setObject:pendingViews forKey:url];
	}
	
}

- (void)receivedImageASI:(UIImage*)image sender:(ImageDownloaderASI*)sender
{
   // image = [RoundedRectImageCreater createRoundedRectImage:image size:image.size];
	if(image)
	{
        image = [RoundedRectImageCreater createRoundedRectImage:image size:image.size];
		[_cache setObject:image forKey:sender._sURL];

		
		NSMutableArray *pendingViews = [_activeDownloads objectForKey:sender._sURL];
		if(pendingViews)
		{
			for(UIImageView *view in pendingViews)
				view.image = image;//[RoundedRectImageCreater createRoundedRectImage:image size:image.size];
		}
	}
	
	[_activeDownloads removeObjectForKey:sender._sURL];
}

- (void)receivedImage:(UIImage*)image sender:(ImageDownloader*)sender
{
    // image = [RoundedRectImageCreater createRoundedRectImage:image size:image.size];
	if(image)
	{
        image = [RoundedRectImageCreater createRoundedRectImage:image size:image.size];
		[_cache setObject:image forKey:sender._sURL];
        
		
		NSMutableArray *pendingViews = [_activeDownloads objectForKey:sender._sURL];
		if(pendingViews)
		{
			for(UIImageView *view in pendingViews)
				view.image = image;//[RoundedRectImageCreater createRoundedRectImage:image size:image.size];
		}
	}
	
	[_activeDownloads removeObjectForKey:sender._sURL];
}

@end
